package org.tamal.servlet.filter;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.tamal.Constants;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * This filter identifies browser.
 * @author Tamal Kanti Nath
 */
public class BrowserFilter implements Filter {

    private static final Logger LOG = Logger.getLogger(BrowserFilter.class.getName());
    private static final DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Empty
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
        if (!Constants.PRODUCTION) {
            return;
        }
        if (!(request instanceof HttpServletRequest)) {
            StringBuffer sb = new StringBuffer("Not a HTTP request.");
            sb.append(" Local Address:" + request.getLocalAddr());
            sb.append(" Local Name:" + request.getLocalName());
            sb.append(" Remote Address:" + request.getRemoteAddr());
            sb.append(" Remote Name:" + request.getRemoteHost());
            LOG.info(sb.toString());
            return;
        }
        HttpServletRequest req = (HttpServletRequest) request;
        String userAgent = req.getHeader(Constants.USER_AGENT);
        if (userAgent == null) {
            StringBuffer sb = new StringBuffer("User-Agent not found.");
            sb.append(" Local Address:" + req.getRequestURL());
            LOG.info(sb.toString());
            return;
        }
        saveUserAgent(userAgent);
    }

    private static void saveUserAgent(String userAgent) {
        Key key = KeyFactory.createKey(Constants.USER_AGENT, Constants.CURRENT);
		Entity entity;
		try {
			entity = ds.get(key);
		} catch (EntityNotFoundException e) {
			entity = new Entity(key);
		}
		Long count = (Long) entity.getProperty(userAgent);
		count = (count == null) ? 1L : count + 1L;
		entity.setProperty(userAgent, count);
		ds.put(entity);
	}

    @Override
    public void destroy() {
        // Empty
    }

}
